<template>
	<view class="goods-detail-wrap">
		<scroll-view scroll-y class="layout-scroll">
			<view class="swiper-box" v-if="swiperList.length > 0">
				<swiper class="swiper" @change="handleChange" circular :indicator-dots="false" :autoplay="autoplay"
					:interval="2000" :duration="500">
					<swiper-item v-for="item in swiperList">
						<view class="swiper-item" v-if="item.type == 'image'">
							<image :src="item.url" mode=""></image>
						</view>
						<view class="swiper-item" v-else>
							<video id="myVideo" :src="item.url" controls :muted="muted"
								:autoplay="videoAutoplay"></video>
						</view>
					</swiper-item>
				</swiper>
				<view class="indicator" v-if="goodsInfo.goodsBanner && currentNum == (swiperList.length - 1)">
				</view>
				<view class="indicator" v-else>
					<view class="indicator-num">{{ currentNum + 1 }}/{{ swiperList.length }}</view>
				</view>
			</view>
			<view class="swiper-box" v-else>
				<image style="width: 100%;height:100%"
					src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/order/goods_nomal.png">
				</image>
			</view>
			<view class="goods-info">
				<view class="price">
					<view class="price-info">
            <view class="new-price" v-if="goodsInfo.useCouponPrice">券后价</view>
						<view class="new-price">
							<text class="icon">￥</text>
              <text>{{goodsInfo.useCouponPrice ? goodsInfo.useCouponPrice.toFixed(2) : goodsInfo.discountPrice ? goodsInfo.discountPrice.toFixed(2): ''}}</text>
						</view>
						<view class="old-price" v-if="goodsInfo.proposalPrice" :class="!goodsInfo.useCouponPrice?'old-price-througth':''">
							￥{{ goodsInfo.proposalPrice.toFixed(2) }}
						</view>
					</view>
					<view class="share" @click="show=true"><u-icon name="share-square" color="#fff"
							size="36"></u-icon>分享</view>
				</view>
				<view class="goods-name">{{ goodsInfo.exhibitionName }}</view>
        <view class="goods-tagList-wrapper" :class="goodsInfo.tagList && goodsInfo.tagList.length ? 'tag-padding' : 'tag-no-padding'">
          <view class="goods-tagList" v-if="goodsInfo.tagList && goodsInfo.tagList.length"
            @click.stop="clickGoodsTagList">
            <view class="goods-tagList-item" v-for="tag in goodsInfo.tagList" :key="tag.id">
              ·<view class="goods-tagList-item-label">{{ tag.name }}</view>
            </view>
          </view>
        </view>
			</view>
			<view class="goods-info-item">
				<view class="title">促销</view>
				<view class="item-content" v-if="goodsInfo.promotionList && goodsInfo.promotionList.length > 0"
					@click.stop="clickPromotionList">
					<view class="promotion" v-for="item in goodsInfo.promotionList" :key="item.sort">
						<!-- @click="openPromotionModal(item)" -->
						<!-- 	<view class="promotion-name">{{  }}</view> -->
						<u-tag :text="item.typeName" :key="item.typeName" bgColor="#FFEFEF" borderColor="#FFB2B2"
							color="#FF7B7B" size="mini" plain plainFill>
						</u-tag>
						<view class="promotion-title">{{ item.title }}</view>
					</view>
				</view>
				<view class="item-content" v-else>
					<text class="promotion-title">暂无促销</text>
				</view>
			</view>
			<view class="goods-info-item">
				<view class="title">购买数量</view>
				<view class="item-content">
					<view class="pay-count">
						<uni-number-box v-model="number" :min="1" />
					</view>
				</view>
			</view>
			<view class="goods-info-item" @click="openService">
				<view class="title">服务说明</view>
				<view class="item-content">
					<view class="server-doc">
						<view class="mr10 icon">
							<u-icon name="checkmark-circle-fill" color="#ff0000" size="30"></u-icon>
							<text class="ml10">上市公司</text>
						</view>
						<view class="mr10 icon">
							<u-icon name="checkmark-circle-fill" color="#ff0000" size="30"></u-icon>
							<text class="ml10">官方正品</text>
						</view>
						<view class="icon">
							<u-icon name="checkmark-circle-fill" color="#ff0000" size="30"></u-icon>
							<text class="ml10">值得信赖</text>
						</view>
					</view>
				</view>
				<view class="right-icon">
					<u-icon name="arrow-right" color="#000" size="30"></u-icon>
				</view>
			</view>
			<view class="goods-info-item">
				<view class="title">购物流程</view>
				<view class="item-content">
					{{ goodsInfo.process || '' }}
				</view>
			</view>
			<view class="goods-info-item" @click="checkedStore">
				<view class="title">门店</view>
				<view class="item-content">
					<text v-if="adressInfo.name">{{adressInfo.name }}</text>
					<text v-else style="color:#8E8E8E">请选择你的服务门店</text>
				</view>
				<view class="right-icon">
					<u-icon name="arrow-right" color="#000" size="30"></u-icon>
				</view>
			</view>
			<view class="goods-info-item" @click="showDatePicker">
				<view class="title">预计到店日期</view>
				<view class="item-content">
					{{ arrivalTime }}
				</view>
				<view class="right-icon">
					<u-icon name="arrow-right" color="#000" size="30"></u-icon>
				</view>
			</view>
			<view class="goods-info-item" style="display: block;">
				<view class="title">规格参数</view>
				<view class="parmas-box" v-if="goodsInfo.properties">
					<view class="table-cell" v-for="(item,index) in goodsInfo.properties" :key="item.propName">
						<text class="title"
							:class="{'end-border':index == goodsInfo.properties.length - 1 }">{{ item.propName}}</text>
						<text class="info"
							:class="{'end-border':index == goodsInfo.properties.length - 1 }">{{ item.propContent}}</text>
					</view>
				</view>
			</view>
			<view class="goods-info-item" style="display: block;">
				<view class="title">图文详情</view>
				<view class="description">
					<view v-html="goodsInfo.description"></view>
				</view>

			</view>
		</scroll-view>

		<view class="goods-detail-nav">
			<uni-goods-nav :fill="false" :options="options" :buttonGroup="buttonGroup" @click="onLookMyCart"
				@buttonClick="onClickButton" />
		</view>
		<u-datetime-picker :visible-item-count="8" :show="showDate" v-model="arrivalTime1" @cancel="closeDatePicker"
			@confirm="sureArrivalTime" :minDate="arrivalTime2" mode="date">
		</u-datetime-picker>
		<!-- 服务说明弹框 -->
		<u-modal :show="serviceModal" title="服务说明" @confirm="serviceModal=false" confirm-color="#DE4442">
			<view class="slot-content">
				<view style="padding: 12px 0;color: rgba(0, 0, 0, 0.45)">暂无说明</view>
			</view>
		</u-modal>
		<!-- 促销弹框 -->
		<u-modal :show="promotionModal" :title="promotionTitle" @confirm="promotionModal=false" confirm-color="#DE4442">
			<view class="slot-content">
				<view style="padding: 12px 0;color: rgba(0, 0, 0, 0.45)">{{promotionContent}}</view>
			</view>
		</u-modal>

		<u-toast ref="uToast"></u-toast>


		<!-- 商品标签 -->
		<u-popup :show="popupShow" :round="20" mode="bottom" @close="popupShow = false" :closeOnClickOverlay="true">
			<view class="popup-content">
				<view class="pc-title">
					<text>{{ popupType === 'tag' ? '商品标签' : '促销说明'}}</text>
					<u-icon name="close" color="#C8C9CC" size="32" @click="popupShow = false"></u-icon>
				</view>
				<view class="pc-list" v-if="popupType === 'tag'">
					<view :class="['pc-item']" v-for="item in popupList" :key="item.id">
						{{ item.name }}
					</view>
				</view>
				<view class="pc-list-pro"
					v-if="popupType === 'pro' && goodsInfo.promotionList && goodsInfo.promotionList.length > 0">
					<view class="pcl-title">促销</view>
					<view class="promotion" v-for="item in goodsInfo.promotionList" :key="item.sort">
						<u-tag :text="item.typeName" :key="item.typeName" bgColor="#FFEFEF" borderColor="#FFB2B2"
							color="#FF7B7B" size="mini" plain plainFill>
						</u-tag>
						<view class="promotion-title">{{ item.title }}</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 分享组件 -->
		<share :isOpen="show" @cancel="show=false" :copyBtn="false" :shareBtn="true" :copyUrl="true" :jfcode="jfcode">
		</share>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import share from '@/components/share.vue'
	export default {
		components: {
			share
		},
		data() {
			return {
				swiperList: [],
				goodsInfo: {},
				number: 1,
				options: [{
					icon: 'cart',
					text: '购物车',
					info: 0
				}],
				arrivalTime: '', //到店时间
				arrivalTime1: Number(new Date()),
				arrivalTime2: Number(new Date()),
				showDate: false,
				buttonGroup: [{
						text: '加入购物车',
						backgroundColor: '#ffa200',
						color: '#fff'
					},
					{
						text: '立即购买',
						backgroundColor: '#ff0000',
						color: '#fff'
					}
				],
				jfcode: '',
				adressInfo: null,
				autoplay: true,
				serviceModal: false,
				promotionModal: false,
				promotionContent: '',
				promotionTitle: '',
				currentNum: 0,
				videoContext: null,
				wifiStatus: false, //是否是wifi环境
				muted: false, //播放静音
				videoAutoplay: false, //视频自动播放
				popupShow: false,
				popupList: [],
				show: false,
				popupType: '' // tag- 商品标签， pro-促销说明
			}
		},
		computed: {
			...mapGetters('user', ['getUserInfo']),
		},
		mounted() {
			this.videoContext = uni.createVideoContext("myVideo", this);
		},
		methods: {
			clickGoodsTagList() {
				this.popupType = 'tag'
				this.popupShow = true
			},
			clickPromotionList() {
				if (!this.goodsInfo.promotionList.length) {
					return false
				}
				this.popupType = 'pro'
				this.popupShow = true
			},

			//wifi是否连接
			getWifiStatus() {
				let that = this
				uni.getNetworkType({
					success: function(res) {
						if (res.networkType == 'wifi') {
							that.wifiStatus = true

						} else {
							that.wifiStatus = false
						}
					}
				});
			},

			//切换
			handleChange(val) {
				this.currentNum = val.detail.current
				if (this.goodsInfo.goodsBanner && val.detail.current == (this.swiperList.length - 1)) {
					this.autoplay = false
					if (this.wifiStatus) {
						this.videoContext.play();
						this.muted = true
					}
				} else {
					this.autoplay = true
					if (this.goodsInfo.goodsBanner) {
						this.videoContext.pause();
					}
				}

			},
			//查看购物车详情
			onLookMyCart() {
				const {
					jfcode
				} = this
				uni.navigateTo({
					url: '/components/cartList',
					success: () => {
						setTimeout(() => {
							uni.$emit(
								'cartSource', {
									path: `/components/goodsDetail?jfcode=${jfcode}`,
									isTabbar: false
								})
						}, 500)
					}
				})
			},
			// 获取购物车商品数量
			async getCartGoodsTotal() {
				const {
					datas
				} = await this.$request({
					url: '/order-center/owner-carts/count',
					method: 'GET'
				})
				this.options[0].info = datas
			},
			// 加入购物车
			async addGoodsToCart() {
				const {
					goodsId
				} = this.goodsInfo
				const {
					number: quantity
				} = this
				try {
					// 加入购物车
					const res = await this.$request({
						url: '/order-center/owner-carts/addOrUpdate',
						data: {
							goodsContexts: [{
								goodsId,
								quantity
							}],
							operateType: 'PART'
						}
					})
					this.getCartGoodsTotal()
					uni.showToast({
						title: '添加成功',
					})

					// 埋点
					this.$uma.trackEvent('add-cart');
					this.autoReport({
						pageName: '商品详情页',
						eventCode: 'add-cart',
						businessId: res.datas[0]
					})

				} catch (err) {
					this.$refs.uToast.show({
						message: err.respMsg || '添加失败',
						position: 'top'
					})
				}
			},
			async buyNow(e) {
				// uni.redirectTo({ url: '/cartPack/paymentSuccess/paymentSuccess' })
				// return
				// 立即购买
				uni.navigateTo({
					url: '/cartPack/confirmOrder/confirmOrder',
					success: (res) => {
						const {
							goodsId,
							exhibitionName,
							images,
							promotionList,
							discountPrice: price
						} = this.goodsInfo
						const {
							number: quantity,
							adressInfo: storeInfo,
							arrivalTime: planArriveTime
						} = this
						res.eventChannel.emit('confirmOrder', {
							sourceType: 'GOOD_DETAIL', // 申明来自商品详情。CART=购物车，GOOD_DETAIL=商品详情
							data: {
								promotionList, //商品标签
								goodsId, // 商品id
								exhibitionName, // 商品名称
								price, // 商品单价
								quantity, // 商品数量
								goodsImges: images[0], // 商品缩略图
								storeInfo, // 门店信息
								planArriveTime, // 到店时间
							}
						})
					}
				})
			},

			// 点击底部右侧按钮
			onClickButton(e) {
				if (e.index == 0) {
					this.addGoodsToCart()
				} else {
					this.buyNow()
				}
			},

			async initData() {
				uni.showLoading({
					title: '加载中...'
				})
				this.swiperList = []
				try {
					const res = await this.$request({
						method: 'GET',
						url: '/product-center/warehouse/goods/getGoodDetails',
						data: {
							jfcode: this.jfcode,
							userId: this.getUserInfo.id
						}
					})
					const datas = this.goodsInfo = res.datas
					this.popupList = res.datas.tagList
					if (datas.images.length > 0) {
						datas.images.forEach(item => {
							let obj = {
								url: item,
								type: 'image'
							}
							this.swiperList.push(obj)
						})
					}
					if (datas.goodsBanner) {
						this.swiperList.push({
							url: datas.goodsBanner,
							type: 'video'
						})

					}
					if (this.goodsInfo.description) {
						this.goodsInfo.description = this.goodsInfo.description.replace(/\<img/gi,
							'<img style="width:100%;height:auto" ')
					}
					console.log(this.goodsInfo.description)
					uni.hideLoading()
				} catch (err) {
					uni.hideLoading()
					this.$refs.uToast.show({
						message: err.respMsg || '请求失败',
						position: 'top',
						duration: 2000
					})
					setTimeout(() => {
						// 分享进来，未登录，页面栈数量只为1
						if(getCurrentPages().length === 1){
							uni.redirectTo({
							  url: '/authPack/login/wxLogin'
							  // url: '/authPack/login/phoneLogin'
							})
						}else {
							uni.navigateBack({
								success: () => {
									uni.$emit('loseGoods')
								}
							})
						}
					}, 2000)
				}

				uni.stopPullDownRefresh();
			},
			//选择门店
			checkedStore() {
				uni.navigateTo({
					url: '/components/selectStore',
					events: {
						//获取下级页面传递回来的参数
						setStoreAdress: data => {
							this.adressInfo = data
						}
					}
				})
			},
			showDatePicker() {
				this.showDate = true
			},
			closeDatePicker() {
				this.showDate = false
			},
			async sureArrivalTime(e) {
				this.showDate = false
				const timeFormat = uni.$u.timeFormat;
				this.arrivalTime = await timeFormat(e.value, 'yyyy-mm-dd');
			},
			//打开服务说明弹框
			openService() {
				this.serviceModal = true
			},
			openPromotionModal(val) {
				console.log(val)
				this.promotionContent = val.content
				this.promotionTitle = val.title
				this.promotionModal = true
			},
			setStoreInfo(options) {
				this.adressInfo = options.data.storeInfo
			}
		},
		onLoad(option) {
			this.jfcode = option.jfcode
			this.initData()
			this.getWifiStatus()

			// 获取从门店详情传入的门店信息
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('storeInfo', this.setStoreInfo)
		},
		onShow() {
			this.getCartGoodsTotal()
		},
		// 分享到聊天
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				return {
					title: `￥${this.goodsInfo.discountPrice}|${this.goodsInfo.exhibitionName}`,
					desc: `阿特拉斯卡友之家`,
					path:`/components/goodsDetail?jfcode=${option.jfcode}`,
					imageUrl: `${this.swiperList.length ? this.swiperList[0].url:'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/order/goods_nomal.png'}`
				}
			}
			return {
			}
		},
	}
</script>

<style lang="scss">
	.goods-detail-wrap {
		box-sizing: border-box;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.mr10 {
			margin-right: 20rpx;
		}

		.ml10 {
			margin-left: 10rpx;
		}

		.layout-scroll {
			box-sizing: border-box;
			flex: 1;
			height: calc(100vh - 100rpx - env(safe-area-inset-bottom));

			.swiper-box {
				height: 800rpx;
				position: relative;

				.indicator {
					position: absolute;
					right: 10rpx;
					bottom: 30rpx;

					.indicator-num {
						padding: 4rpx 0;
						background-color: rgba(0, 0, 0, 0.35);
						border-radius: 200rpx;
						width: 70rpx;
						text-align: center;
						color: #fff;
						font-size: 12px;
					}
				}

				.swiper {
					height: 100%;

					.swiper-item {
						width: 100%;
						height: 100%;
					}

					image {
						width: 100%;
						height: 100%;
					}

					video {
						width: 100%;
						height: 100%;
					}
				}
			}
		}

		.goods-info {
			background: #fff;
			padding: 0;

			.goods-name {
				text-shadow: 0 0 0.1px currentcolor;
				margin-bottom: 20rpx;
				word-wrap: break-all;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				text-shadow: 0 0 0.1px currentcolor;
				line-clamp: 2;
				-webkit-box-orient: vertical;
				padding: 20rpx;
			}

      .tag-padding {
        padding-bottom: 20rpx;
      }
      .tag-no-padding {
        padding-bottom: 0;
      }
      .goods-tagList-wrapper {
        .goods-tagList {
          display: flex;
          flex-wrap: wrap;
          max-height: 68rpx;
          overflow: hidden;
          padding: 0 20rpx;
          margin-bottom: 10rpx;

          .goods-tagList-item {
            display: flex;
            align-items: center;
            font-size: 12px;
            color: #808080;
            margin-right: 24rpx;

            .goods-tagList-item-label {
              margin-left: 8rpx;
            }
          }
        }
      }

			.price {
				display: flex;
				align-items: center;
				justify-content: space-between;
				background: url('https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/index/price-bg.png');
				background-size: 100% 100%;
				height: 120rpx;
				padding: 0 20rpx;
				position: relative;
                margin-top: -20rpx;
				.price-info {
					display: flex;
					align-items: center;
				}

				.new-price {
					color: #fff;
					margin-right: 20rpx;
					font-weight: bolder;

					.icon {
						font-size: 12px;
					}
				}

				.old-price {
					color: #fff;
					font-size: 12px;
				}
        .old-price-througth {
					text-decoration: line-through;
        }

				.share {
					display: flex;
					color: #fff;
					font-size: 14px;
					height: 100%;
					line-height: 120rpx;

					/deep/ .u-icon {
						margin-right: 10rpx;
					}
				}
			}
		}

		.goods-info-item {
			padding: 20rpx;
			background: #fff;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			margin-top: 20rpx;
			position: relative;
			font-size: 12px;

			.title {
				color: #8E8E8E;
				padding-right: 20rpx;
			}

			.right-icon {
				position: absolute;
				right: 20rpx;
				top: 30%
			}

			.item-content {
				flex: 1;
				position: relative;
				font-size: 12px;
				padding-right: 30rpx;

				.promotion-title {
					color: rgba(0, 0, 0, 0.45);
					padding-left: 10rpx;
				}

				.promotion {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					position: relative;
					margin-bottom: 16rpx;

					.promotion-name {
						color: #F67F77;
						background: #FAEEEF;
						padding: 4rpx;
						border-radius: 8rpx;
						border: 1px solid #F9B3B8;
						margin-right: 6rpx;
					}


					.right-icon {
						right: -2rpx;
						top: 20%
					}
				}

				.pay-count {
					width: 200rpx;
					float: right;
				}

				.server-doc {
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.icon {
						display: flex;
						justify-content: flex-start;
					}
				}
			}

			.parmas-box {
				width: 100%;
				margin-top: 20rpx;

				.table-cell {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					font-size: 12px;

					.title {
						width: 200rpx;
						color: #8E8E8E;
						padding: 10rpx 16rpx;
						border: 1px solid #eee;
						border-bottom: none;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;

					}

					.info {
						flex: 1;
						padding: 10rpx 16rpx;
						border: 1px solid #eee;
						border-left: none;
						border-bottom: none;
					}

					.end-border {
						border-bottom: 1px solid #eee;
					}
				}
			}

			.description {
				width: 100%;
				margin-top: 20rpx;
				overflow: hidden;
				overflow-y: auto;

				img {
					width: 100%;
				}
			}
		}

		.goods-detail-nav {
			width: 100vw;
			flex: 0;

			/deep/ .uni-tab__dot {
				padding: 0 !important;
				width: 35rpx;
				height: 35rpx;
				line-height: 35rpx;
				text-align: center;
				border-radius: 50%;
			}

			/deep/ .uni-tab__icon {
				width: 60rpx;

				.uniui-cart {
					font-size: 25px !important;
				}
			}
		}
	}

	.u-modal__title {
		border-bottom: 1px solid #eee;
		padding-bottom: 20rpx;
	}

	// 门店服务标签
	.popup-content {
		width: 100%;
		display: flex;
		flex-direction: column;
		background-color: #F7F8FA;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		overflow: hidden;

		.pc-title {
			width: 100%;
			text-align: center;
			padding: 26rpx 0;
			font-size: 16px;
			color: #323233;
			background-color: #ffffff;
			position: relative;

			/deep/ .u-icon {
				position: absolute;
				right: 40rpx;
				top: 34rpx;
			}
		}

		.pc-list {
			display: flex;
			flex-wrap: wrap;
			// justify-content: space-between;
			box-sizing: border-box;
			padding: 40rpx;
			background-color: #ffffff;

			.pc-item {
				padding: 12rpx 48rpx;
				background-color: #F2F2F2;
				font-size: 12px;
				color: #262626;
				margin: 0 20rpx 20rpx 0;
				border-radius: 32rpx;
			}
		}

		.pc-list-pro {
			box-sizing: border-box;
			padding: 40rpx;
			background-color: #ffffff;

			.pcl-title {
				color: rgba(0, 0, 0, 0.65);
				margin: 30rpx 0;
				font-size: 16px;
			}

			.promotion-title {
				color: rgba(0, 0, 0, 0.45);
				padding-left: 10rpx;
			}

			.promotion {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				position: relative;
				margin-bottom: 16rpx;

				.promotion-name {
					color: #F67F77;
					background: #FAEEEF;
					padding: 4rpx;
					border-radius: 8rpx;
					border: 1px solid #F9B3B8;
					margin-right: 6rpx;
				}

				.right-icon {
					right: -2rpx;
					top: 20%
				}
			}
		}
	}
</style>